#include "apps.h"
#include "esp_log.h"

#define RETRY_INIT_DELAY 2000
#define RUN_DELAY 1000

void printStatus(uint8_t err);

float ahtValue; // to store T/RH result

void aht20_loop()
{
  static uint32_t last = 0;
  static int state = 0;
  static uint32_t mark = 0;
  uint8_t err = 0;
  if (millis() - last < 100)
  {
    return;
  }
  last = millis();

  switch (state)
  {
  case 0:
    if (aht20.begin(38, 39, 100000, 1000) != true)
    {
      log_e("AHT2x not connected or fail to load calibration coefficient");
      state = 1;
    }
    else
    {
      log_i("AHT2x initialization successful");
      state = 2;
    }
    mark = millis();
    break;
  case 1:
    if (millis() - mark < RETRY_INIT_DELAY)
    {
      break;
    }
    else
    {
      state = 0;
    }
    break;
  case 2:
    /* DEMO - 2, temperature call will read 6-bytes via I2C, humidity will use same 6-bytes */
    ahtValue = aht20.readTemperature(); // read 6-bytes via I2C, takes 80 milliseconds
    if (ahtValue != AHTXX_ERROR)        // AHTXX_ERROR = 255, library returns 255 if error occurs
    {
      log_i("Temperature: %f +-0.3C", ahtValue);
    }
    else
    {
      err = aht20.getStatus();
      printStatus(err); // print temperature command status
      if (err != AHTXX_NO_ERROR)
      {
        state = 0;
      }
    }
    ahtValue = aht20.readHumidity(AHTXX_USE_READ_DATA); // use 6-bytes from temperature reading, takes zero milliseconds!!!

    if (ahtValue != AHTXX_ERROR) // AHTXX_ERROR = 255, library returns 255 if error occurs
    {
      // log_i("Humidity...:  %f +-2%",ahtValue);
      state = 3;
    }
    else
    {
      err = aht20.getStatus();
      printStatus(err); // print temperature command status
      if (err != AHTXX_NO_ERROR)
      {
        state = 0;
      }
    }
    mark = millis();
    break;
  case 3:
    if (millis() - mark < RUN_DELAY) // 10 * 100ms = 1s
    {
      break;
    }
    else
    {
      state = 2;
    }
    break;

  default:
    state = 0;
    break;
  }
}

/**************************************************************************/
/*
    printStatus()

    Print last command status
*/
/**************************************************************************/
void printStatus(uint8_t err)
{
  switch (err)
  {
  case AHTXX_NO_ERROR:
    log_e("no error");
    break;

  case AHTXX_BUSY_ERROR:
    log_e("sensor busy, increase polling time");
    break;

  case AHTXX_ACK_ERROR:
    log_e("sensor didn't return ACK, not connected, broken, long wires (reduce speed), bus locked by slave (increase stretch limit)");
    break;

  case AHTXX_DATA_ERROR:
    log_e("received data smaller than expected, not connected, broken, long wires (reduce speed), bus locked by slave (increase stretch limit)");
    break;

  case AHTXX_CRC8_ERROR:
    log_e("computed CRC8 not match received CRC8, this feature supported only by AHT2x sensors");
    break;

  default:
    log_e("unknown status");
    break;
  }
}
